#include "CManage.h"

CManage::CManage()
{
    //ctor
    m_user = NULL;
    m_map = new CBuildMap;
    m_max.resize(3);
}

CManage::~CManage()
{
    //dtor
    DELPOINT(m_map);
    DELPOINT(m_user);
}

void CManage::Init()
{
    cout<<"Please input the filename stored the user message"<<endl;
    string file;
    cin>>file;
    ifstream ifs (file.c_str());
    if (!ifs.is_open())
    {
       cout<<"Open file fail!"<<endl;
       exit(0);
    }
    else
    {
        while(!ifs.eof())
        {
            m_user = new CUser;
            m_user->Read(&ifs);
            m_userlist.push_back(m_user);
        }
    }
}

void CManage::InitGame()
{
    int i;
    for (i=0;i<3;i++)
        m_max[i]=0;
}

bool CManage::Login()
{
    cout<<"Please input your username"<<endl;
    string name;
    cin>>name;
    unsigned int i;
    for (i=0;i<m_userlist.size();i++)
    {
        if ( m_userlist[i]->Islogin (name) )
        {
            this->m_user = m_userlist[i];
            return true;
        }
    }
    cout<<"login failed"<<endl;
    return false;
}

void CManage::RecordMax()
{
    if ( m_map->GetMark() > m_max[m_level-1] )
        m_max[m_level-1] = m_map->GetMark() ;
}

void CManage::PrintMax(int level)
{
    system("clear");
    cout<<"The max score of level "<<m_level<<" is "<<m_max[m_level-1]<<endl;
    cout<<endl<<endl<<endl<<endl;
}

void CManage::PrintMark()
{
    system("clear");
    cout<<"Your mark is ";
    cout<<this->m_map->GetMark()<<endl;
    cout<<endl<<endl<<endl<<endl;
}

void CManage::SelectOption()
{
    cout<<"please choose a selection below"<<endl;
    cout<<"1 --> Print my mark"<<endl;
    cout<<"2 --> Print the best grade of level input"<<endl;
    cout<<"3 --> Change the user"<<endl;
    cout<<"4 --> Replay the game"<<endl;
    cout<<"5 --> Exit the program"<<endl;
    int tmp_level;
    int choosen;
    cin>>choosen;
    switch (choosen)
    {
        case 1: PrintMark();
                SelectOption();
                break;
        case 2: cout<<"Please input the level"<<endl;
                cin>>tmp_level;
                PrintMax(tmp_level);
                SelectOption();
                break;
        case 3: if (Login())
                  Run();
                break;
        case 4: Run();
                break;
        case 5: cout<<"The progress is over"<<endl;
                sleep(1);
                exit (0);
    }
}

void CManage::Run()
{
    InitGame();
    m_map->ShowOption();
    cin>>m_level>>m_shape;
    m_map->RunGame(m_level,m_shape);
    RecordMax();
    SelectOption();
}
